package com.imoocdl.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * 后台:
 *  1,pom文件引入 webSocket包
 *  2,项目启动时 要创建好 ServerEndpointExporter类 如com.imoocdl.config.WebSocketConfig
 *  3,创建 websocket类(本类)
 *  前台 order / list.ftl
 *
 * Created by pc on 2018/7/27.
 */
@Component
@ServerEndpoint("/webSocket")
@Slf4j
public class WebSocket {
    private Session session;  //
    private static CopyOnWriteArraySet<WebSocket> webSocketSet = new CopyOnWriteArraySet<>(); //websocket 容器

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);
        log.info("[webSocket消息] 有新的连接 ,总数:{}",webSocketSet.size());
    }

    @OnClose
    public void onClose(){
        webSocketSet.remove(this);
        log.info("[webSocket消息] 连接断开,总数{}",webSocketSet.size());
    }

    /**
     * 收到消息
     */
    @OnMessage
    public void onMessage(String msg){
     log.info("[webSocket消息] 收到消息:{}",msg);
    }
    /**
     * 发送消息
     */
    public void sendMessage(String message){
       for(WebSocket  webSocket:webSocketSet){
            log.info("[webSocket消息] 广播消息,message={}",message);
            try{
                webSocket.session.getBasicRemote().sendText(message);
            }catch (Exception e){
                e.printStackTrace();
            }
       }
    }
}
